package com.gxsyh.nantie.user.management.provider.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gxsyh.nantie.commons.configure.rabbitmq.RabbitMQConfig;
import com.gxsyh.nantie.commons.dto.PageHelpDTO;
import com.gxsyh.nantie.commons.dto.ResponseResult;
import com.gxsyh.nantie.commons.dto.SendLogResult;
import com.gxsyh.nantie.commons.utils.OkHttpClientUtil;
import com.gxsyh.nantie.user.management.provider.controller.dto.DepartmentAddPeopleParam;
import com.gxsyh.nantie.user.management.provider.controller.dto.DetailedInformationDTO;
import com.gxsyh.nantie.user.management.provider.controller.dto.InsterDepartmentParam;
import com.gxsyh.nantie.user.management.provider.domain.TbDepartment;
import com.gxsyh.nantie.user.management.provider.domain.TbUser;
import com.gxsyh.nantie.user.management.provider.domain.UserInfo;
import com.gxsyh.nantie.user.management.provider.domain.UserInfoList;
import com.gxsyh.nantie.user.management.provider.service.*;
import okhttp3.ResponseBody;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**用户信息Controller
 * @email yom535@outlook.com
 * @author: 刘锋嘉(Liu Fengjia)
 * @date: 2020/1/3
 * @time: 13:36
 * @Description:
 */
@Transactional
@RestController
public class UserInfoController {
    @Resource
    UserInfoListService userInfoListService;

    @Resource
    UserInfoService userInfoService;

    @Resource
    TbDepartmentService tbDepartmentService;

    @Resource
    TbDepartmentUserService tbDepartmentUserService;

    @Resource
    TbUserService tbUserService;

    @Resource
    AmqpTemplate amqpTemplate;

    @Value("${base.config.leaf.url}")
    String LEAF_URL;

    /**
     * 获取用户信息
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/user/info")
    public ResponseResult<UserInfo> userInfo() throws Exception {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String userId = authentication.getName();
        UserInfo userInfo = userInfoService.selectUserInfo(userId);
        return new ResponseResult<>(HttpStatus.OK.value(),"获取用户信息成功",userInfo);
    }

    /**
     * 获取 用户管理 列表
     * @param pageNum
     * @return
     */
    @GetMapping(value = "/user/list/{pageNum}")
    public ResponseResult<PageHelpDTO> userList(@PathVariable int pageNum){
        PageHelper.startPage(pageNum,5,"tb_user.created DESC");
        PageInfo<UserInfoList> pageInfo=new PageInfo<>(userInfoListService.getUserInfoList());
        List<UserInfoList> userInfoList = pageInfo.getList();
        PageHelpDTO pageHelpDTO=new PageHelpDTO();
        pageHelpDTO.setPages(pageInfo.getPages());
        pageHelpDTO.setTotal(pageInfo.getTotal());
        pageHelpDTO.setData(userInfoList);
        return new ResponseResult<>(200,"用户信息",pageHelpDTO);
    }

    /**
     * 搜索用户信息
     * @param pageNum
     * @param search
     * @return
     */

    @GetMapping(value = "/user/list/{search}/{pageNum}")
    public ResponseResult<PageHelpDTO> userListSearch(@PathVariable int pageNum,@PathVariable String search){
        PageHelper.startPage(pageNum,5,"tb_user.created DESC");
        PageInfo<UserInfoList> pageInfo=new PageInfo<>(userInfoListService.getUserInfoListSearch(search));
        List<UserInfoList> userInfoList = pageInfo.getList();
        PageHelpDTO pageHelpDTO=new PageHelpDTO();
        pageHelpDTO.setPages(pageInfo.getPages());
        pageHelpDTO.setTotal(pageInfo.getTotal());
        pageHelpDTO.setData(userInfoList);
        return new ResponseResult<>(200,"搜索用户信息",pageHelpDTO);
    }



    /**
     * 查询子部门
     * @param departmentId
     * @return
     */
    @GetMapping(value = "/user/departments/subset")
    public ResponseResult<List<TbDepartment>> queryingSubsetDepartmentsId(@RequestParam Long departmentId){
        List<TbDepartment> tbDepartments = tbDepartmentService.queryingSubsetDepartmentsId(departmentId);
        return new ResponseResult<List<TbDepartment>>(HttpStatus.OK.value(),"查询子部门",tbDepartments);
    }

    /**
     * 添加子部门
     * @param insterDepartmentParam
     * @param httpServletResponse
     * @return
     */
    @PostMapping(value = "/user/department/inster")
    public ResponseResult<Void> insterDepartment(@RequestBody InsterDepartmentParam insterDepartmentParam, HttpServletResponse httpServletResponse) throws IOException {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String userId = authentication.getName();
        if (insterDepartmentParam.getMainDepartmentId()==88)
        {
            httpServletResponse.setStatus(500);
            return new ResponseResult<>(HttpStatus.INTERNAL_SERVER_ERROR.value(),"此部门没有下级部门");
        }
        if (insterDepartmentParam.getAddedDepartment().isEmpty()){
            httpServletResponse.setStatus(500);
            return new ResponseResult<>(HttpStatus.INTERNAL_SERVER_ERROR.value(),"请检查输入格式");
        }
        ResponseBody body = OkHttpClientUtil.getInstance().getData(LEAF_URL + "insterdepartment").body();
        int i = tbDepartmentService.insterDepartment(Long.valueOf(body.string()),Long.valueOf(insterDepartmentParam.getMainDepartmentId()), insterDepartmentParam.getAddedDepartment(),0);
        if (i>0)
        {
            //                使用消息队列发送日志
            SendLogResult sendLogResult = new SendLogResult();
            sendLogResult.setUserId(Long.valueOf(userId));
            sendLogResult.setUsername(insterDepartmentParam.getAddedDepartment());
            sendLogResult.setInfo("向部门ID:"+insterDepartmentParam.getMainDepartmentId()+"添加部门:"+insterDepartmentParam.getAddedDepartment());
            amqpTemplate.convertAndSend(RabbitMQConfig.SEND_LOG_QUEUE,sendLogResult);
//                end消息队列发送日志

            return new ResponseResult<>(HttpStatus.OK.value(),"添加成功",null);
        }
        else {
            httpServletResponse.setStatus(500);
            return new ResponseResult<>(HttpStatus.INTERNAL_SERVER_ERROR.value(),"请检查输入格式");
        }
    }
    /**
     * 通过部门ID查用户列表
     */
    @GetMapping(value = "/user/list/department/{departmentId}/{pageNum}")
    public ResponseResult<PageHelpDTO> departmentUserListOnDepartmentId(@PathVariable Long departmentId,@PathVariable int pageNum){
        PageHelper.startPage(pageNum,5,"tb_user.created DESC");
        PageInfo<UserInfoList> pageInfo=new PageInfo<>(userInfoListService.departmentUserListOnDepartmentId(departmentId));
        List<UserInfoList> result = pageInfo.getList();
        PageHelpDTO pageHelpDTO=new PageHelpDTO();
        pageHelpDTO.setPages(pageInfo.getPages());
        pageHelpDTO.setTotal(pageInfo.getTotal());
        pageHelpDTO.setData(result);
        return new ResponseResult<>(200,"部门下的用户信息",pageHelpDTO);
    }
    /**
     * 查询未加入部门的人 部门ID88
     */
    @GetMapping(value = "/user/list/not/deparement/{pageNum}")
    public ResponseResult<PageHelpDTO> notDeparement(@PathVariable int pageNum){
        PageHelper.startPage(pageNum,10,"tb_user.created DESC");
        PageInfo<UserInfoList> pageInfo=new PageInfo<>(userInfoListService.selectPeopleWhoHaveNotJoinedTheDepartment());
        List<UserInfoList> result = pageInfo.getList();
        PageHelpDTO pageHelpDTO=new PageHelpDTO();
        pageHelpDTO.setPages(pageInfo.getPages());
        pageHelpDTO.setTotal(pageInfo.getTotal());
        pageHelpDTO.setData(result);
        return new ResponseResult<>(200,"未加入部门的人员信息",pageHelpDTO);
    }
    /**
     * 向部门添加人员 或 移出
     */
    @PostMapping(value = "/user/deparement/inster/user")
    public ResponseResult<Void> departmentAddPeopleParam(@RequestBody DepartmentAddPeopleParam departmentAddPeopleParam){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        int result=0;
        Long[] userId = departmentAddPeopleParam.getUserId();
        for (Long aLong : userId) {
            if (aLong.equals(Long.valueOf(authentication.getName()))){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return new ResponseResult<>(HttpStatus.INTERNAL_SERVER_ERROR.value(),"不可以移入/移出自己",null);
            }
            int i = tbDepartmentUserService.updateUserDepartment(aLong, departmentAddPeopleParam.getDepartmentId());
            result+=i;
        }
        //                使用消息队列发送日志
        SendLogResult sendLogResult = new SendLogResult();
        sendLogResult.setUserId(Long.valueOf(authentication.getName()));
        sendLogResult.setUsername(Arrays.toString(departmentAddPeopleParam.getUserId()));
        sendLogResult.setInfo("向部门"+departmentAddPeopleParam.getDepartmentId()+"移入或移出人员"+Arrays.toString(departmentAddPeopleParam.getUserId()));
        amqpTemplate.convertAndSend(RabbitMQConfig.SEND_LOG_QUEUE,sendLogResult);
//                end消息队列发送日志
        return new ResponseResult<>(HttpStatus.OK.value(),"更新"+result+"条",null);
    }
    /**
     * 通过父级ID查询所有下级部门
     */
    @GetMapping(value = "/user/subset/deparement/user/search")
    public ResponseResult<List<UserInfoList>> selectSubsetDepartment(@RequestParam String select,HttpServletResponse response){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String userId = authentication.getName();
        UserInfo userInfo = userInfoService.selectUserInfo(userId);
        List<TbDepartment> tbDepartments = tbDepartmentService.selectSubsetDepartment(userInfo.getDepartmentId());
        List list=new ArrayList();
        tbDepartments.forEach(tbDepartment -> {
            list.add(tbDepartment.getId());
        });
        List<UserInfoList> result = userInfoListService.selectSubsetUser(select, list);
        if (result.isEmpty()){
            response.setStatus(404);
            return new ResponseResult<>(HttpStatus.NOT_FOUND.value(),"未搜索到，请检查输入内容。",result);
        }
        return new ResponseResult<>(HttpStatus.OK.value(),"搜索成功",result);
    }

    /**
     * 获取详细信息
     * @param userId
     * @return
     */
    @GetMapping(value = "/user/detailed/information")
    public ResponseResult<DetailedInformationDTO> detailedInformation(@RequestParam long userId){
        UserInfo userInfo = userInfoService.selectUserInfo(String.valueOf(userId));
        TbUser tbUser = tbUserService.selectOne(userId);
        List<TbDepartment> tbDepartments = tbDepartmentService.selectParentDepartment(userInfo.getDepartmentId());
        //Collections.reverse(tbDepartments);
        DetailedInformationDTO detailedInformationDTO=new DetailedInformationDTO();
        detailedInformationDTO.setId(tbUser.getId());
        detailedInformationDTO.setUsername(tbUser.getUsername());
        detailedInformationDTO.setJobNumber(tbUser.getJobNumber());
        detailedInformationDTO.setName(tbUser.getName());
        if (tbUser.getSubsidyStatus()==0){
            detailedInformationDTO.setSubsidyStatus("无");
        }else if (tbUser.getSubsidyStatus()==1){
            detailedInformationDTO.setSubsidyStatus("有");
        }
        detailedInformationDTO.setInfo(tbUser.getInfo());
        if (tbUser.getUserStatus()==0){
            detailedInformationDTO.setUserStatus("不启用");
        }else if (tbUser.getUserStatus()==1){
            detailedInformationDTO.setUserStatus("启用");
        }
        detailedInformationDTO.setPhone(tbUser.getPhone());
        detailedInformationDTO.setCreated(tbUser.getCreated());
        detailedInformationDTO.setUpdated(tbUser.getUpdated());
        detailedInformationDTO.setParentDepartment(tbDepartments);


        return new ResponseResult<>(HttpStatus.OK.value(),"用户详细信息",detailedInformationDTO);
    }

    /**
     * 删除用户
     */
    @GetMapping("/user/delete")
    public ResponseResult<Void> deleteUser(@RequestParam long userId,HttpServletResponse response){

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication.getName().equals(String.valueOf(userId))){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new ResponseResult<>(HttpStatus.INTERNAL_SERVER_ERROR.value(),"不可以删除自己",null);
        }

        int tbUserResult = tbUserService.deleteUser(userId);
        if (tbUserResult==1){
            //                使用消息队列发送日志
            SendLogResult sendLogResult = new SendLogResult();
            sendLogResult.setUserId(Long.valueOf(authentication.getName()));
            sendLogResult.setUsername(String.valueOf(userId));
            sendLogResult.setInfo("删除了用户ID为"+userId+"的账号");
            amqpTemplate.convertAndSend(RabbitMQConfig.SEND_LOG_QUEUE,sendLogResult);
//                end消息队列发送日志
            return new ResponseResult<>(HttpStatus.OK.value(),"删除成功",null);
        }else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            response.setStatus(500);
            return new ResponseResult<>(HttpStatus.INTERNAL_SERVER_ERROR.value(),"删除失败",null);
        }
    }

}
